'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import GlassInput from '@/components/ui/GlassInput';
import PasswordInput from '@/components/ui/PasswordInput';
import ThemeToggle from '@/components/ui/ThemeToggle';
import { LogIn } from 'lucide-react';

export default function LoginPage() {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  });
  const [errors, setErrors] = useState<{ username?: string; password?: string }>({});

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrors({});

    // Basic validation
    if (!formData.username) {
      setErrors(prev => ({ ...prev, username: '请输入用户名' }));
      return;
    }
    if (!formData.password) {
      setErrors(prev => ({ ...prev, password: '请输入密码' }));
      return;
    }

    setLoading(true);
    
    try {
      const { authApi } = await import('@/lib/api');
      const { useAuthStore } = await import('@/store/authStore');
      
      // 1. Call login API
      const response = await authApi.login(formData.username, formData.password);
      
      // 2. Save token
      useAuthStore.getState().setToken(response.access_token);
      
      // 3. Get user info
      const userInfo = await authApi.getCurrentUser();
      
      // 4. Save user info to store
      useAuthStore.getState().setUser(userInfo);
      
      // 5. Redirect to dashboard
      router.push('/dashboard');
    } catch (error: any) {
      setErrors({ 
        password: error.message || '登录失败，请检查用户名和密码' 
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      {/* Theme toggle in top right */}
      <div className="fixed top-6 right-6 z-50">
        <ThemeToggle />
      </div>

      {/* Login card */}
      <GlassCard className="w-full max-w-md p-8 animate-fade-in">
        {/* Logo and title */}
        <div className="text-center mb-8">
          <h1 className="text-4xl font-extrabold mb-2">
            <span className="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300">
              思和智库
            </span>
          </h1>
          <p className="text-lg font-semibold bg-gradient-to-r from-indigo-500 to-purple-500 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400 mb-2">
            Sihe KnowledgeHub
          </p>
          <p className="text-sm font-medium bg-gradient-to-r from-indigo-600 via-purple-500 to-pink-500 bg-clip-text text-transparent dark:from-indigo-400 dark:via-purple-400 dark:to-pink-400">
            汇聚智慧，赋能政企
          </p>
        </div>

        {/* Login form */}
        <form onSubmit={handleSubmit} className="space-y-4">
          <GlassInput
            label="用户名"
            placeholder="请输入用户名"
            value={formData.username}
            onChange={(e) => setFormData({ ...formData, username: e.target.value })}
            error={errors.username}
          />

          <PasswordInput
            label="密码"
            placeholder="请输入密码"
            value={formData.password}
            onChange={(e) => setFormData({ ...formData, password: e.target.value })}
            error={errors.password}
          />

          <div className="flex items-center justify-between text-sm">
            <label className="flex items-center text-indigo-600 dark:text-indigo-400 hover:text-purple-600 dark:hover:text-purple-400 cursor-pointer transition-colors font-medium">
              <input type="checkbox" className="mr-2 rounded text-indigo-600 focus:ring-indigo-500" />
              记住我
            </label>
            <a href="#" className="text-indigo-600 dark:text-indigo-400 hover:text-purple-600 dark:hover:text-purple-400 transition-colors font-medium">
              忘记密码？
            </a>
          </div>

          <GlassButton
            type="submit"
            variant="primary"
            size="lg"
            loading={loading}
            className="w-full"
          >
            <LogIn className="mr-2 h-5 w-5" />
            登录
          </GlassButton>
        </form>

        {/* 注册提示 */}
        <div className="mt-6 text-center">
          <p className="text-sm text-gray-700 dark:text-white/70">
            还没有账号？{' '}
            <Link
              href="/register"
              className="font-semibold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400 hover:from-indigo-700 hover:to-purple-700 dark:hover:from-indigo-300 dark:hover:to-purple-300 transition-all"
            >
              立即注册
            </Link>
          </p>
        </div>

      </GlassCard>
    </div>
  );
}

